//
//  HEPayManager.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/10/29.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEPayManager.h"
#import "CommonMacros.h"

@interface HEPayManager ()

@property (nonatomic, strong) NSString *wxAppId;
@property (nonatomic, strong) NSString *wxAppSecret;

@end

@implementation HEPayManager

#pragma mark - LifeCycle
+(instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static HEPayManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[HEPayManager alloc] init];
        instance.wxAppId = @"wxbf3e4ddc81817d38";
        instance.wxAppSecret = @"0d142750ff99e681c906520a3bca042e";

    });
    return instance;
}

#pragma mark - 微信支付配置
- (void)setupWXPay {
    [WXApi registerApp:self.wxAppId universalLink:@"https://www.honglutec.com/app/"];
}


#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    
    // =============== 获得的微信支付回调 ============
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg,*strTitle = [NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                
                [self paySucess];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationPaySuccess object:nil];
                break;
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationPayFailure object:nil];
                break;
        }
    }
    // =============== 获得的微信登录授权回调 ============
    else if ([resp isMemberOfClass:[SendAuthResp class]])  {
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode != 0 ) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [Dialog toastBottom:@"微信授权失败"];
            });
            return;
        }
        //授权成功获取 OpenId
        NSString *code = aresp.code;
        [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationOtherAuthSuccess object:code];
    }
}

- (void)onReq:(BaseReq *)req {

}



#pragma mark - 支付宝

- (void)senAliPayRequest:(NSString *)orderParmas {
    NSString *appScheme = @"alipay2021002129687799"; //appScheme是你在项目中添加的URL Type(别写错)
    NSString *orderString = orderParmas; //aParam[@"payInfo"];
    
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        int statusCode = [resultDic[@"resultStatus"]  intValue];
         
        [[HEPayManager sharedManager] payManagerCallbackWithPayType:HEOrderPayTypeAliPay results:resultDic];
    }];
}

- (void)payManagerCallbackWithPayType:(HEOrderPayType)payType results:(NSDictionary *)results {
    NSLog(@"result = %@",results);
    NSString *code = results[@"resultStatus"];
    if ([@"9000" isEqualToString:code]) {
        
      [self paySucess];
      [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationPaySuccess object:nil];
    }else {
      [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationPayFailure object:nil];
    }
}

#pragma mark - 支付成功 订单信息同步处理
- (void)paySucess {
    HEOrderModel *info = [HEPayManager sharedManager].order;

//    [self orderSyncReq];
//
//    if (info.channel == HEChannelTypeSpinalReh) {
//        [self orderSyncSpinalReq];
//    }else if (info.channel == HEChannelTypeHomeCare) {
//        [self orderSyncHomeCareReq];
//    }
    
}

// 支付成功后同步订单属性
- (void)orderSyncReq {
    
    UserInfo *user = [[UserManager sharedUserManager] getUserInfo];

    // 支付成功后同步订单属性
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KInst parameters:@{@"order_id":[NSNumber numberWithInteger:[HEPayManager sharedManager].order.id], @"usid": user.id} success:^(id  _Nonnull responseObject) {
//        NSLog(@"response：  %@", [responseObject mj_JSONString]);

    } failure:^(NSError * _Nonnull error) {
        
    }];
}

// 线下脊柱康复订单支付成功后需要同步一些订单信息
- (void)orderSyncSpinalReq {
    UserInfo *user = [[UserManager sharedUserManager] getUserInfo];
    HEOrderModel *info = [HEPayManager sharedManager].order;
    
    NSString *addres = [NSString stringWithFormat:@"%@%@%@%@",info.receiverProvince, info.receiverCity, info.receiverRegion, info.receiverDetailAddress];
    
    NSMutableDictionary *dict = @{
        @"product_id": [NSNumber numberWithInteger:info.goodsId],
        @"schedule": info.serviceTime,
        @"service_addr": addres,
        @"usid": user.id
        }.mutableCopy;

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KInst parameters:dict success:^(id  _Nonnull responseObject) {

     } failure:^(NSError * _Nonnull error) {
         
     }];
}

// 居家照料订单支付成功后同步订单消息
- (void)orderSyncHomeCareReq {

    // TODO:// 支付成功需要加入逻辑判断
    // 线下脊柱康复订单支付成功后需要同步一些订单信息
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KInst parameters:@{@"orderId":[NSNumber numberWithInteger:[HEPayManager sharedManager].order.id]} success:^(id  _Nonnull responseObject) {

     } failure:^(NSError * _Nonnull error) {
         
     }];
}


#pragma mark - 微信授权登录


@end
